<template>
	<page-meta :page-style="'overflow:' + (showPopup ? 'hidden' : 'visible')"></page-meta>
	<view class="container">
		<uni-nav-bar title="录入分类信息" fixed statusBar :border="false" leftIcon='back'
			@clickLeft="goBackPage"></uni-nav-bar>
		<text class="tip">
			Tip：在此录入商品分类信息，随后前往
			<text class="tip-link" @click="gotoGoodsPage">“录入商品信息（点此跳转）”</text>
			页面按照分类完成商品录入
		</text>
		<uni-collapse accordion v-if="Array.isArray(list) && list.length ">
			<uni-collapse-item v-for="item in list" :key="item._id" :title="item.title" titleBorder="true">
				<view class="listBox">
					<uni-list v-for="cItem in item.children" :key="cItem._id" :border="false">
						<uni-list-item showArrow clickable :title="cItem.title"
							@click="(e) => editPopup(cItem, editTypes.child, editOption.edit)" />
					</uni-list>
				</view>
				<view class="addInsetBox" hover-class="addInsetBox-active" hover-stay-time="100"
					@click="() => editPopup({ title: item.title, parentData: item, placeholder:'请输入子类名称' },editTypes.child, editOption.add)">
					<uni-icons type="plusempty" size="15" color="#297ff6"></uni-icons>
					<text class="addInsetBox-text">新增子类</text>
				</view>
				<view class="clearBox" hover-class="clearBox-active" hover-stay-time="100"
					@click="(e) => editPopup(item, editTypes.parent, editOption.edit)">
					<uni-icons type="gear" size="15" color="#666"></uni-icons>
					<text class="clearBox-text">编辑分类</text>
				</view>
			</uni-collapse-item>
		</uni-collapse>
		<empty-page v-else />

		<view class="addBox" hover-class="addBox-active" hover-stay-time="100"
			@click="() => editPopup({}, editTypes.parent, editOption.add)">
			<uni-icons type="plus" size="17" color="#297ff6"></uni-icons>
			<text class="addBox-text">新增分类</text>
		</view>

		<uni-popup ref="delDialog" type="dialog">
			<uni-popup-dialog type="error" cancelText="取消" confirmText="确定" title="危险操作提示"
				:content="`确定要删除该${editInfo.optType}吗？`" @confirm="delConfirm" @close="delCancle" />
		</uni-popup>

		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog v-bind:title="dynamicOptions.title" mode="base" type="info" @confirm="submitInput"
				@close="cancleInput" beforeClose>
				<uni-easyinput v-bind:placeholder="dynamicOptions.placeholder" v-model="inputValue" autoHeight trim />
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup class="popup" ref="selectPopup" safeArea backgroundColor="#fff" borderRadius="6px 6px 0 0"
			@maskClick="changeShowPopup">
			<view class="popup-options">
				<text class="popup-btn popup-btn-danger" @click="delPopup"
					v-if="editInfo.optPre === editOption.edit">删除</text>
				<text class="popup-title">{{editInfo.optPre}}{{editInfo.optType}}</text>
				<text class="popup-btn popup-btn-primary" @click="submitPopup">保存</text>
			</view>
			<view class="popup-content">
				<text class="popup-content-title" v-if="editInfo?.parentData?.title !== undefined">
					所属分类：&nbsp;{{editInfo.parentData.title}}
				</text>
				<view class="popup-content-component">
					<text class="popup-content-name">名称：&nbsp;</text>
					<uni-easyinput v-model="editInfo.title" placeholder="请输入" autoHeight trim />
				</view>
				<view class="popup-content-component" v-if="editInfo.optType === editTypes.parent">
					<text class="popup-content-name">缩略图：&nbsp;</text>
					<uni-file-picker v-model='editInfo.icon' return-type='object'></uni-file-picker>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		getCurrentInstance,
		reactive,
		ref
	} from 'vue';
	import {
		onShow,
		onPullDownRefresh,
	} from '@dcloudio/uni-app'
	import {
		editOption,
		editTypes
	} from './const.js'
	const {
		proxy
	} = getCurrentInstance()

	const showPopup = ref(false)
	const list = ref([])
	const inputValue = ref('')
	let editInfo = ref({})
	let dynamicOptions = reactive({
		parentData: {},
		title: '',
		placeholder: ''
	})

	const goBackPage = () => uni.navigateBack()
	const gotoGoodsPage = () => uni.redirectTo({
		url: '/pages/admin/components/goodsInfo/index'
	})

	const cutDownText = (title, num = -1) => {
		let res = title
		if (res.length > num) {
			res = res.slice(0, num) + '...'
		}
		return res
	}

	/** 提交输入事件 */
	const submitInput = async () => {
		if (inputValue.value === '') {
			uni.showToast({
				title: '请输入分类名称',
				duration: 1000,
				icon: 'none'
			})
		} else {
			const mallCategories = uniCloud.importObject('mall-categories')
			try {
				let param = {
					title: inputValue.value
				}
				if (dynamicOptions.parentData) {
					param.parent_id = dynamicOptions.parentData._id
				}
				await mallCategories.addData(param)
				uni.showToast({
					title: '新增成功',
					icon: 'success'
				})
				getData({
					customUI: true
				})
			} catch (err) {
				console.log('错误 ', err.errCode, '：', err.errMsg)
			}
			proxy.$refs.inputDialog.close()
			showPopup.value = false
		}
	}

	// 取消输入事件
	const cancleInput = () => {
		uni.hideToast()
		proxy.$refs.inputDialog.close()
		showPopup.value = false
	}

	const delConfirm = async () => {
		const mallCategories = uniCloud.importObject('mall-categories')
		try {
			await mallCategories.deleteData({
				_id: editInfo.value._id,
			})
			uni.showToast({
				title: '删除成功',
				icon: 'success'
			})
			getData({
				customUI: true
			})
			proxy.$refs.delDialog.close()
			showPopup.value = false
			editInfo.value = {}
		} catch (err) {
			console.log('错误 ', err.errCode, '：', err.errMsg)
		}
	}

	const delCancle = () => {
		proxy.$refs.selectPopup.open('bottom')
	}

	// 监听 Popup 弹窗状态改变
	const changeShowPopup = (e) => showPopup.value = false

	const delPopup = () => {
		proxy.$refs.delDialog.open()
		proxy.$refs.selectPopup.close()
	}

	const editPopup = (data, optType, optPre) => {
		if (optType === editTypes.child && optPre === editOption.add) {
			inputValue.value = ''
			dynamicOptions = reactive({
				...data,
				title: `${cutDownText(data.title, 8)}-${optPre}`
			})
			proxy.$refs.inputDialog.open()
		} else {
			editInfo.value = {
				...data,
				optType,
				optPre
			}
			proxy.$refs.selectPopup.open('bottom')
		}
		showPopup.value = true
	}

	const submitPopup = async () => {
		const {
			title,
			icon,
			optType,
			optPre,
			_id
		} = editInfo.value || {}
		if (title === '') {
			return uni.showToast({
				title: `请输入${optType}名称`,
				icon: 'error'
			})
		}
		const mallCategories = uniCloud.importObject('mall-categories')
		try {
			switch (optPre) {
				case editOption.add:
					await mallCategories.addData({
						title,
						icon
					})
					break;
				case editOption.edit:
					await mallCategories.updateData({
						_id,
						data: editInfo.value
					})
					break;
				default:
					break;
			}
			uni.showToast({
				title: `保存成功`,
				icon: 'success'
			})
			getData({
				customUI: true
			})
			proxy.$refs.selectPopup.close()
			showPopup.value = false
			editInfo.value = {}
		} catch (err) {
			console.log('错误 ', err.errCode, '：', err.errMsg)
		}
	}

	const getData = async (options = {
		loadingOptions: {
			title: '加载中...',
			mask: true
		},
		errorOptions: {
			type: 'toast'
		}
	}) => {
		const mallCategories = uniCloud.importObject('mall-categories', options)
		try {
			const res = await mallCategories.getData()
			list.value = res?.data
		} catch (err) {
			console.log('错误 ', err.errCode, '：', err.errMsg)
		}
		uni.stopPullDownRefresh()
	}

	onPullDownRefresh(() => getData())
	onShow(() => {
		getData()
	})
</script>

<style lang="scss" scoped>
	@import url("/styles/common.scss");

	.container {
		padding-bottom: 68px;
	}

	.listBox {
		margin: 0 12px 0 16px;
	}

	.tip {
		display: block;
		font-size: 14px;
		text-indent: 2em;
		color: #666;
		background-color: var(--background-color);
		box-shadow: inset 0 2px 6px 0 rgba(0, 0, 0, 0.04);
		line-height: 24px;
		padding: 6px 16px;
		border-top: 1px solid #eee;
		border-bottom: 1px solid #eee;

		&-link {
			color: #54a1ff;
			text-decoration: underline;
		}
	}

	.addInsetBox {
		line-height: 42px;
		height: 42px;
		color: var(--primary-color);
		font-size: 14px;
		padding: 0 24px 0 28px;
		transition: all 0.24s;

		&-text {
			margin-left: 8px;
		}

		&-active {
			background-color: whitesmoke;
		}
	}

	.clearBox {
		line-height: 42px;
		height: 42px;
		color: #666;
		font-size: 14px;
		padding: 0 24px 0 28px;
		transition: all 0.24s;

		&-text {
			margin-left: 8px;
		}

		&-active {
			background-color: whitesmoke;
		}
	}

	.addBox {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		text-align: center;
		line-height: 56px;
		height: 56px;
		color: var(--primary-color);
		font-size: 16px;
		border-top: 1px solid #ddd;
		transition: all 0.24s;
		background-color: white;

		&-text {
			margin-left: 6px;
		}

		&-active {
			background-color: whitesmoke;
		}
	}

	.popup {
		width: 100%;
		box-sizing: border-box;

		&-options {
			width: 100%;
			padding: 12px 10px;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;
		}

		&-content {
			padding: 26px;
			display: flex;
			flex-direction: column;
			gap: 16px 0;
			background-color: var(--background-color);

			&-title {
				font-size: 14px;
				color: #666;
			}

			&-component {
				display: flex;
				align-items: center;
			}

			&-name {
				font-size: 14px;
				color: #666;
			}
		}

		&-btn {
			&-danger {
				color: #d45050;
			}

			&-primary {
				color: var(--primary-color);
			}
		}
	}
</style>